<template>
  <n-grid-item span="5">
    <n-form :model="voiceConfig" ref="formRef" :rules="rules">
      <n-form-item>
          <n-alert style="width: 100%" :show-icon="false" type="warning">原创不能选择视频原声</n-alert>
      </n-form-item>
      <n-form-item label="方案类型" path="planType">
        <n-select v-model:value="voiceConfig.planType" :options="planOptions">
        </n-select>
      </n-form-item>
      <n-form-item label="声源类型" path="voiceType" v-if="voiceConfig.planType==='systemVoice'">
        <n-select v-model:value="voiceConfig.voiceType" :options="voiceTypeOptions" @update:value="voiceTypeSelect">
        </n-select>
      </n-form-item>
      <n-form-item label="声音选择" path="voiceName" v-if="voiceConfig.planType==='systemVoice'">
        <n-select
            :loading="voiceOptionLoading"
            v-model:value="voiceConfig.voiceName"
            :options="voiceOptions"
            clearable>
        </n-select>
      </n-form-item>
      <n-form-item label="音速" v-if="voiceConfig.planType==='systemVoice'">
        <n-slider v-model:value="voiceConfig.speed" :min="0.8" :max="2" :step="0.1"/>
      </n-form-item>
      <n-form-item label="音量" v-if="voiceConfig.planType==='systemVoice'">
        <n-slider v-model:value="voiceConfig.volume" :min="0.8" :max="2" :step="0.1"/>
      </n-form-item>
      <n-form-item label="音调" v-if="voiceConfig.planType==='systemVoice'" >
        <n-slider v-model:value="voiceConfig.pitch" :min="0.8" :max="2" :step="0.1"/>
      </n-form-item>
      <n-form-item label="停顿时间" v-if="voiceConfig.planType==='systemVoice'">
        <n-select
            v-model:value="voiceConfig.pauseType"
            :options="pauseTypeOption">
        </n-select>
      </n-form-item>
      <n-button block type="primary" @click="voiceTest" :loading="voiceOptionLoading" v-if="voiceConfig.planType==='systemVoice'">试听</n-button>
      <div hidden>
        <audio
            ref="audioPlayer"
            :autoplay="true"
            controls
            style="width: 100%;margin-top: 10px"
        ></audio>
      </div>
    </n-form>
  </n-grid-item>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {FormItemRule, useMessage} from 'naive-ui';
// @ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {voiceController} from "@/api/voice/ttsController.api";
import {ttsDict} from '@/dictionary/ttsDict'

const voiceOptions = ref([])
const voiceOptionLoading = ref(false)
const audioPlayer = ref(null)
const { voiceTypeOptions, pauseTypeOption,planOptions} = ttsDict()


const voiceConfig: Tts.voiceConfig = reactive({
  voiceType: '',
  voiceName: '',
  volume: 1.0,
  speed: 1.0,
  pitch: 1.0,
  pauseType: 'normal',
  planType: 'systemVoice'
})

const checked = ref(false)
const formRef: any = ref(null)
const message = useMessage();


const validatePlanType =  (rule: FormItemRule, value: string) => {
  if(voiceConfig.planType === 'systemVoice'){
    if(value === '' || value === undefined || value === null){
      return new Error('该值不能为空！')
    }
  }
  return true
}

const rules = {
  planType:{
    required: true,
    message: '请选择方案类型',
    trigger: ['blur', 'change']
  },
  voiceName: {
    // required: true,
    validator: validatePlanType,
    message: '请选择声音',
    trigger: ['blur', 'change']
  },
  voiceType: {
    validator: validatePlanType,
    message: '请选择声音类型',
    trigger: ['blur', 'change']
  },
  speed: {
    validator: validatePlanType,
    message: '请填写音速',
    trigger: ['blur', 'change']
  },
  volume: {
    validator: validatePlanType,
    message: '请填写音量',
    trigger: ['blur', 'change']
  },
  pitch: {
    validator: validatePlanType,
    message: '请填写音调',
    trigger: ['blur', 'change']
  },
}



onMounted(() => {
  // getVoiceOption('free')
})

const getVoiceOption = (voiceType: string) => {
  voiceOptionLoading.value = true
  voiceOptions.value = []
  const param = {
    type: voiceType
  }
  voiceController.listVoiceActors(param).then(res => {
    if (res.code === 200) {
      console.log(res.data)
      res.data.forEach((item: any) => {
        // @ts-ignore
        voiceOptions.value.push({
          label: item.localName + "," + (item.gender === 'Male' ? '男' : '女') + "," + item.age + "," + item.localeNameZh,
          value: item.shortName
        })
      })
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    voiceOptionLoading.value = false
  })
}

// 选中声音类型
const voiceTypeSelect = async (value: string) => {
  getVoiceOption(value);
}

const voiceTest = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      voiceOptionLoading.value = true
      const ttsTask = {
        content: '您好,我是蜡笔小新',
        ttsType: voiceConfig.voiceType,
        voiceName: voiceConfig.voiceName,
        rate: voiceConfig.speed,
        volume: voiceConfig.volume,
        pitch: voiceConfig.pitch
      }
      voiceController.previewAudio(ttsTask).then(res => {
        voiceOptionLoading.value = false
        if (res.code === 200) {
          audioPlayer.value.src = fileFunction.getViewFilePath({userFileId: res.data})
          // 设置音频的url
        } else {
          message.error(res.message);
        }
      }).finally(() => {
        voiceOptionLoading.value = false
      })
    }
  })
}
const loadConfig = (configJSON: string) => {
  const config = JSON.parse(configJSON)
  voiceConfig.planType = config.planType
  voiceConfig.pitch = config.pitch
  voiceConfig.speed = config.speed
  voiceConfig.volume = config.volume
  voiceConfig.voiceType = config.voiceType
  getVoiceOption(config.voiceType)
  voiceConfig.pauseType = config.pauseType
  voiceConfig.voiceName = config.voiceName
}

const getConfig = async () => {
  return new Promise(async (resolve, reject) => {
    formRef.value?.validate((errors) => {
      if (!errors) {
        resolve(voiceConfig)
      } else {
        reject(false);
      }
    })
  })
}

defineExpose({
  getConfig, loadConfig
})
</script>
